home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / shelve.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  10KB  |  273 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Manage shelves of pickled objects.
  5.  
  6. A "shelf" is a persistent, dictionary-like object.  The difference
  7. with dbm databases is that the values (not the keys!) in a shelf can
  8. be essentially arbitrary Python objects -- anything that the "pickle"
  9. module can handle.  This includes most class instances, recursive data
  10. types, and objects containing lots of shared sub-objects.  The keys
  11. are ordinary strings.
  12.  
  13. To summarize the interface (key is a string, data is an arbitrary
  14. object):
  15.  
  16.         import shelve
  17.         d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
  18.  
  19.         d[key] = data   # store data at key (overwrites old data if
  20.                         # using an existing key)
  21.         data = d[key]   # retrieve a COPY of the data at key (raise
  22.                         # KeyError if no such key) -- NOTE that this
  23.                         # access returns a *copy* of the entry!
  24.         del d[key]      # delete data stored at key (raises KeyError
  25.                         # if no such key)
  26.         flag = d.has_key(key)   # true if the key exists; same as "key in d"
  27.         list = d.keys() # a list of all existing keys (slow!)
  28.  
  29.         d.close()       # close it
  30.  
  31. Dependent on the implementation, closing a persistent dictionary may
  32. or may not be necessary to flush changes to disk.
  33.  
  34. Normally, d[key] returns a COPY of the entry.  This needs care when
  35. mutable entries are mutated: for example, if d[key] is a list,
  36.         d[key].append(anitem)
  37. does NOT modify the entry d[key] itself, as stored in the persistent
  38. mapping -- it only modifies the copy, which is then immediately
  39. discarded, so that the append has NO effect whatsoever.  To append an
  40. item to d[key] in a way that will affect the persistent mapping, use:
  41.         data = d[key]
  42.         data.append(anitem)
  43.         d[key] = data
  44.  
  45. To avoid the problem with mutable entries, you may pass the keyword
  46. argument writeback=True in the call to shelve.open.  When you use:
  47.         d = shelve.open(filename, writeback=True)
  48. then d keeps a cache of all entries you access, and writes them all back
  49. to the persistent mapping when you call d.close().  This ensures that
  50. such usage as d[key].append(anitem) works as intended.
  51.  
  52. However, using keyword argument writeback=True may consume vast amount
  53. of memory for the cache, and it may make d.close() very slow, if you
  54. access many of d\'s entries after opening it in this way: d has no way to
  55. check which of the entries you access are mutable and/or which ones you
  56. actually mutate, so it must cache, and write back at close, all of the
  57. entries that you access.  You can call d.sync() to write back all the
  58. entries in the cache, and empty the cache (d.sync() also synchronizes
  59. the persistent dictionary on disk, if feasible).
  60. '''
  61.  
  62. try:
  63.     from cPickle import Pickler, Unpickler
  64. except ImportError:
  65.     from pickle import Pickler, Unpickler
  66.  
  67.  
  68. try:
  69.     from cStringIO import StringIO
  70. except ImportError:
  71.     from StringIO import StringIO
  72.  
  73. import UserDict
  74. __all__ = [
  75.     'Shelf',
  76.     'BsdDbShelf',
  77.     'DbfilenameShelf',
  78.     'open']
  79.  
  80. class _ClosedDict(UserDict.DictMixin):
  81.     '''Marker for a closed dict.  Access attempts raise a ValueError.'''
  82.     
  83.     def closed(self, *args):
  84.         raise ValueError('invalid operation on closed shelf')
  85.  
  86.     __getitem__ = __setitem__ = __delitem__ = keys = closed
  87.     
  88.     def __repr__(self):
  89.         return '<Closed Dictionary>'
  90.  
  91.  
  92.  
  93. class Shelf(UserDict.DictMixin):
  94.     """Base class for shelf implementations.
  95.  
  96.     This is initialized with a dictionary-like object.
  97.     See the module's __doc__ string for an overview of the interface.
  98.     """
  99.     
  100.     def __init__(self, dict, protocol = None, writeback = False):
  101.         self.dict = dict
  102.         if protocol is None:
  103.             protocol = 0
  104.         self._protocol = protocol
  105.         self.writeback = writeback
  106.         self.cache = { }
  107.  
  108.     
  109.     def keys(self):
  110.         return self.dict.keys()
  111.  
  112.     
  113.     def __len__(self):
  114.         return len(self.dict)
  115.  
  116.     
  117.     def has_key(self, key):
  118.         return key in self.dict
  119.  
  120.     
  121.     def __contains__(self, key):
  122.         return key in self.dict
  123.  
  124.     
  125.     def get(self, key, default = None):
  126.         if key in self.dict:
  127.             return self[key]
  128.  
  129.     
  130.     def __getitem__(self, key):
  131.         
  132.         try:
  133.             value = self.cache[key]
  134.         except KeyError:
  135.             f = StringIO(self.dict[key])
  136.             value = Unpickler(f).load()
  137.             if self.writeback:
  138.                 self.cache[key] = value
  139.             
  140.  
  141.         return value
  142.  
  143.     
  144.     def __setitem__(self, key, value):
  145.         if self.writeback:
  146.             self.cache[key] = value
  147.         f = StringIO()
  148.         p = Pickler(f, self._protocol)
  149.         p.dump(value)
  150.         self.dict[key] = f.getvalue()
  151.  
  152.     
  153.     def __delitem__(self, key):
  154.         del self.dict[key]
  155.         
  156.         try:
  157.             del self.cache[key]
  158.         except KeyError:
  159.             pass
  160.  
  161.  
  162.     
  163.     def close(self):
  164.         self.sync()
  165.         
  166.         try:
  167.             self.dict.close()
  168.         except AttributeError:
  169.             pass
  170.  
  171.         
  172.         try:
  173.             self.dict = _ClosedDict()
  174.         except (NameError, TypeError):
  175.             self.dict = None
  176.  
  177.  
  178.     
  179.     def __del__(self):
  180.         if not hasattr(self, 'writeback'):
  181.             return None
  182.         None.close()
  183.  
  184.     
  185.     def sync(self):
  186.         if self.writeback and self.cache:
  187.             self.writeback = False
  188.             for key, entry in self.cache.iteritems():
  189.                 self[key] = entry
  190.             
  191.             self.writeback = True
  192.             self.cache = { }
  193.         if hasattr(self.dict, 'sync'):
  194.             self.dict.sync()
  195.  
  196.  
  197.  
  198. class BsdDbShelf(Shelf):
  199.     '''Shelf implementation using the "BSD" db interface.
  200.  
  201.     This adds methods first(), next(), previous(), last() and
  202.     set_location() that have no counterpart in [g]dbm databases.
  203.  
  204.     The actual database must be opened using one of the "bsddb"
  205.     modules "open" routines (i.e. bsddb.hashopen, bsddb.btopen or
  206.     bsddb.rnopen) and passed to the constructor.
  207.  
  208.     See the module\'s __doc__ string for an overview of the interface.
  209.     '''
  210.     
  211.     def __init__(self, dict, protocol = None, writeback = False):
  212.         Shelf.__init__(self, dict, protocol, writeback)
  213.  
  214.     
  215.     def set_location(self, key):
  216.         (key, value) = self.dict.set_location(key)
  217.         f = StringIO(value)
  218.         return (key, Unpickler(f).load())
  219.  
  220.     
  221.     def next(self):
  222.         (key, value) = self.dict.next()
  223.         f = StringIO(value)
  224.         return (key, Unpickler(f).load())
  225.  
  226.     
  227.     def previous(self):
  228.         (key, value) = self.dict.previous()
  229.         f = StringIO(value)
  230.         return (key, Unpickler(f).load())
  231.  
  232.     
  233.     def first(self):
  234.         (key, value) = self.dict.first()
  235.         f = StringIO(value)
  236.         return (key, Unpickler(f).load())
  237.  
  238.     
  239.     def last(self):
  240.         (key, value) = self.dict.last()
  241.         f = StringIO(value)
  242.         return (key, Unpickler(f).load())
  243.  
  244.  
  245.  
  246. class DbfilenameShelf(Shelf):
  247.     '''Shelf implementation using the "anydbm" generic dbm interface.
  248.  
  249.     This is initialized with the filename for the dbm database.
  250.     See the module\'s __doc__ string for an overview of the interface.
  251.     '''
  252.     
  253.     def __init__(self, filename, flag = 'c', protocol = None, writeback = False):
  254.         import anydbm as anydbm
  255.         Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
  256.  
  257.  
  258.  
  259. def open(filename, flag = 'c', protocol = None, writeback = False):
  260.     """Open a persistent dictionary for reading and writing.
  261.  
  262.     The filename parameter is the base filename for the underlying
  263.     database.  As a side-effect, an extension may be added to the
  264.     filename and more than one file may be created.  The optional flag
  265.     parameter has the same interpretation as the flag parameter of
  266.     anydbm.open(). The optional protocol parameter specifies the
  267.     version of the pickle protocol (0, 1, or 2).
  268.  
  269.     See the module's __doc__ string for an overview of the interface.
  270.     """
  271.     return DbfilenameShelf(filename, flag, protocol, writeback)
  272.  
  273.